package com.why.whypaydemo.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.why.whypaydemo.confing.WeChatConfig;
import com.why.whypaydemo.service.WexinPCServiceImpl;
import com.why.whypaydemo.util.WXPayUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;

@RestController
@RequestMapping(value = "/wxpay")
public class WeXinPCController {

    @Resource
    WexinPCServiceImpl wexinPCService;
    @Resource
    private WeChatConfig weChatConfig;

    /**
     * 微信支付回调
     */
    @PostMapping("/321")
    public String orderCallback() {
        return "321";
    }

    /**
     * PC支付
     */
    @GetMapping(value = "/pcpay")
    public void pcPay(HttpServletResponse response) {
        String s=null;
        try {
             s = wexinPCService.unifiedOrder();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(s == null) {
            throw new  NullPointerException();
        }

        try{
            //生成二维码配置
            Map<EncodeHintType,Object> hints =  new HashMap<>();

            //设置纠错等级
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            //编码类型
            hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");

            BitMatrix bitMatrix = new MultiFormatWriter().encode(s, BarcodeFormat.QR_CODE,400,400,hints);
            OutputStream out =  response.getOutputStream();

            MatrixToImageWriter.writeToStream(bitMatrix,"png",out);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 微信支付回调
     */
    @PostMapping("/order/callback")
    public void orderCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

        InputStream inputStream =  request.getInputStream();

        //BufferedReader是包装设计模式，性能更搞
        BufferedReader in =  new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        StringBuffer sb = new StringBuffer();
        String line ;
        while ((line = in.readLine()) != null){
            sb.append(line);
        }
        in.close();
        inputStream.close();
        Map<String,String> callbackMap = WXPayUtil.xmlToMap(sb.toString());
        System.out.println(callbackMap.toString());

        SortedMap<String,String> sortedMap = WXPayUtil.getSortedMap(callbackMap);

        //判断签名是否正确
        if(WXPayUtil.isCorrectSign(sortedMap,weChatConfig.getKey())){

            if("SUCCESS".equals(sortedMap.get("result_code"))){

                String outTradeNo = sortedMap.get("out_trade_no");


//                if(dbVideoOrder != null && dbVideoOrder.getState()==0){  //判断逻辑看业务场景
//                    VideoOrder videoOrder = new VideoOrder();
//                    videoOrder.setOpenid(sortedMap.get("openid"));
//                    videoOrder.setOutTradeNo(outTradeNo);
//                    videoOrder.setNotifyTime(new Date());
//                    videoOrder.setState(1);
//                    int rows = videoOrderService.updateVideoOderByOutTradeNo(videoOrder);
//                    if(rows == 1){ //通知微信订单处理成功
//                        response.setContentType("text/xml");
//                        response.getWriter().println("success");
//                        return;
//                    }
//                }
            }
        }
        //都处理失败
        response.setContentType("text/xml");
        response.getWriter().println("fail");

    }
}
